import { values } from 'lodash'
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { 
  DEFAULT_SCORE,
  COLOR_SCORE_SIZE, 
  COLOR_SCORE_MAX,
  POINT_SCORE_SIZE, 
  POINT_SCORE_MAX 
} from '@/utils/variable'
import { useColorRef, usePointRef } from '@/composables/useScore'
import { TColor, TPoint } from '@/utils/types'

const useScoreStore = defineStore('score', () => {
  const wins = ref(0)
  const total = ref(DEFAULT_SCORE)
  const colorScore = useColorRef()
  const pointScore = usePointRef()
  const checkScore = () => {
    const k1 = values(colorScore.value).every(k => k === 0)
    const k2 = values(pointScore.value).every(k => k === 0)
    return k1 && k2
  }
  const checked = computed(() => {
    const k = checkScore()
    return {
      k1: k,
      k2: k && wins.value !== 0
    }
  })
  const toLeft = () => { 
    if (!checked.value.k1) return
    const add = wins.value * 2 || 1
    if (total.value - add >= 0) {
      wins.value += add
      total.value -= add
    }
  }
  const toRight = () => {
    if (!checked.value.k1) return
    if (wins.value > 0) {
      total.value += wins.value
      wins.value = 0
    }
  }

  const setColor = (key: TColor) => {
    const newScore = colorScore.value[key]  + COLOR_SCORE_SIZE
    if (newScore <= COLOR_SCORE_MAX) {
      total.value -= COLOR_SCORE_SIZE
      colorScore.value[key] = newScore
    }
  }
  const setScore = (key: TPoint) => {
    const newScore = pointScore.value[key] + POINT_SCORE_SIZE
    if (newScore <= POINT_SCORE_MAX) {
      total.value -= POINT_SCORE_SIZE
      pointScore.value[key] = newScore
    }
  }
  return { 
    wins,
    total,
    toLeft,
    toRight,
    setColor,
    setScore,
    checked,
    colorScore,
    pointScore
  }
})

export default useScoreStore